package com.woniu.tmscommons.utils;

import io.minio.MinioClient;
import io.minio.ObjectWriteResponse;
import io.minio.PutObjectArgs;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;

public class MinioUtil {
    public static final String ENDPOINT = "http://47.120.28.163:9000";
    public static final String ACCESS_KEY = "minioadmin";
    public static final String SECRET_KEY = "minioadmin";
    public static final String BUCKET_NAME = "tms-images";


    public static MinioClient getMinioClient() {
        return MinioClient.builder().endpoint(ENDPOINT).credentials(ACCESS_KEY, SECRET_KEY).build();
    }
    /**
     * 上传文件
     * @param file
     * @return
     * @throws Exception
     */
    public static String upload(MultipartFile file) throws Exception {
        MinioClient minioClient = getMinioClient();
        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        String newFilename = UUID.randomUUID().toString().replace("-", "");
        PutObjectArgs putObjectArgs = PutObjectArgs.builder().bucket(BUCKET_NAME).object(newFilename + suffix)
                .stream(file.getInputStream(), file.getSize(), -1).contentType(file.getContentType())
                .build();
        ObjectWriteResponse objectWriteResponse = minioClient.putObject(putObjectArgs);
        if (objectWriteResponse.object()==null){
            return null;
        }
        return ENDPOINT+"/"+BUCKET_NAME+"/"+newFilename+suffix;
    }
}
